package com.apexsoft.assets.base;

import com.alibaba.fastjson.JSON;
import com.apexsoft.assets.base.aspect.LogAspect;
import com.apexsoft.assets.base.model.Result;
import com.apexsoft.assets.base.exception.BizException;
import com.apexsoft.assets.base.request.RequestInfoModel;
import com.apexsoft.assets.base.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.*;
import java.util.regex.Matcher;

/**
 * Package Name:  com.apexsoft.crm.connOracle
 * Created by on  2018/8/3 13:08
 * Author: yuwenxing
 * Version:
 * Des: Oracle中的结果集直接返回
 */
@Intercepts(@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
@Slf4j
@Component
public class MybatisInterceptor implements Interceptor {

    @Autowired
    LogAspect logAspect;

    private static final String CACHE_NAMESPACE = "LOG";

    private static final String TOTAL_ROWS="I_TOTALROWS";
    private static final String PAGING="I_PAGING";
    private static final String PAGE_NO="I_PAGENO";
    private static final String PAGE_LENGTH="I_PAGELENGTH";
    private static final String RESULT="O_RESULT";
    private static final String CODE="O_CODE";
    private static final String NOTE="O_NOTE";
    private static final String COLIST="O_COLIST";
    private static final String ID="O_ID";

    private Properties properties;


    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        // 获取到节点的id,即sql语句的id
        String sqlId = ms.getId();
        Object params = args[1];
        // BoundSql就是封装myBatis最终产生的sql类
        BoundSql boundSql = ms.getBoundSql(params);
        // 获取节点的配置
        Configuration configuration = ms.getConfiguration();
        String sql = showSql(configuration, boundSql);
        //sql写入request信息，以便方法结束调用后统一插入日志
        addSql2RequstInfo(sql);

        StatementType type = ((MappedStatement) args[0]).getStatementType();
        if(StatementType.CALLABLE.equals(type)){
            Map call;
            if(params instanceof MapperMethod.ParamMap){
                call = (MapperMethod.ParamMap)params;
            }else {
                call = convertObjectToMap(params);
            }
            if(call.containsKey(TOTAL_ROWS) && !(call.get(TOTAL_ROWS) instanceof Number)) {
                call.put(TOTAL_ROWS, -1);
            }
            if(call.containsKey(PAGING) && !(call.get(PAGING) instanceof Number)){
                long currentPage = (long) call.getOrDefault(PAGE_NO,-1L);
                long pageSize = (long) call.getOrDefault(PAGE_LENGTH, -1L);
                if(currentPage>=0 && pageSize>0){
                    call.putIfAbsent(PAGING, 1);
                }else{
                    call.putIfAbsent(PAGING, 0);
                }
            }

            // 调用存储过程
            log.info("Mapper {} Call [{}] begins with parameters: {}", sqlId, sql, call);
            long beginTime = System.currentTimeMillis();
            Object object = invocation.proceed();
            long endTime = System.currentTimeMillis();
            long duration = endTime-beginTime;
            if(!(params instanceof MapperMethod.ParamMap)){
                //重新拼接调用过程后的返回值
                call = convertObjectToMap(params);
            }
            log.info("Mapper {} Call [{}] ends in {}ms, with parameters: {}", sqlId, sql, duration, call);
            List<ResultMap> resultMaps = ms.getResultMaps();
            if(params instanceof MapperMethod.ParamMap){
                return postProcessForCall(call, resultMaps, object);
            }else {
                postProcessForCall(call, resultMaps, object);
                return object;
            }
        }else {
            // 调用SQL
            log.info("Mapper {} SQL [{}] begins", sqlId, sql);
            long beginTime = System.currentTimeMillis();
            Object object = invocation.proceed();
            long endTime = System.currentTimeMillis();
            long duration = endTime-beginTime;
            log.info("Mapper {} SQL [{}] ends in {}ms, with result: {}", sqlId, sql, duration, JSON.toJSONString(object));
            return object;
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private static Object postProcessForCall(@NotNull Map call, List<ResultMap> resultMaps, Object invocationReturn){
        if(call.containsKey(CODE) && call.get(CODE)!=null) {
            if(call.get(CODE) instanceof Integer && (Integer)call.get(CODE)<0){
                // 避免数据库异常信息直接暴露在前端
                log.error("数据库请求异常.参数信息为:{}", call);
                if(!CollectionUtils.isEmpty(resultMaps) && Result.class.equals(resultMaps.get(0).getType())){
                    return buildSimpleResult(call);
                } else{
                    throw new BizException((Integer) call.get(CODE), call.getOrDefault(NOTE, "系统错误！请稍后再试").toString());
                }
            }

            if (call.containsKey(RESULT)) {
                if(call.containsKey(COLIST) && call.get(COLIST)!=null){
                    List<Map<String,Object>> list = (List<Map<String,Object>>)call.get(RESULT);
                    List<Map> resultList = new ArrayList<>();
                    if(!CollectionUtils.isEmpty(list)){
                        for(Map<String,Object> temp : list){
                            //将CLOB转成String类型
                            Map<String,String> result = new HashMap<>();
                            for (String key : temp.keySet()){
                                if (temp.get(key) instanceof Clob){
                                    Clob clob = (Clob)temp.get(key);
                                    String str = null;
                                    try{
                                        str = ResultUtil.ClobToString(clob);
                                    }catch (SQLException | IOException e) {
                                        log.error("MyBatis拦截器ClobToString发生异常", e);
                                    }
                                    temp.put(key,str);
                                }
                                result.put(key,String.valueOf(temp.get(key)).replace("null",""));
                            }
                            result.put("COLIST",String.valueOf(call.get(COLIST)));
                            resultList.add(result);
                        }
                    }
                    return resultList;
                }else if(call.get(RESULT) instanceof List){
                    return buildResultList(call);
                }
                return call.get(RESULT);
            }

            if (resultMaps.isEmpty() && call.containsKey(ID)){
                //出参为map 并且不存在result的情况
                List<Map<String,Object>> resultList=new ArrayList<>();
                Map<String,Object> res=new HashMap<>();
                res.put("code",(Integer) call.get(CODE));
                res.put("note",(String) call.get(NOTE));
                res.put("id",(Integer) call.get(ID));
                resultList.add(res);
                return resultList;
            }

            return buildSimpleResult(call);
        }else if(call.containsKey(RESULT)){
            if(call.get(RESULT) instanceof List){
                return buildResultList(call);
            }
            return call.get(RESULT);
        }
        if(invocationReturn==null
                || invocationReturn instanceof List && ((List)invocationReturn).isEmpty()){
            log.info("return object null");
            List result = new ArrayList();
            result.add(call);
            return result;
        }
        return invocationReturn;
    }

    private static List<Result> buildSimpleResult(@NotNull Map call) {
        Result result = new Result();
        result.setCode((Integer) call.get(CODE));
        result.setNote((String) call.get(NOTE));
        List<Result> resultList = new ArrayList<>();
        resultList.add(result);
        return resultList;
    }

    private static List buildResultList(@NotNull Map call){
        List resultList = (List)call.get(RESULT);
        Integer totalRows =  (Integer) call.getOrDefault(TOTAL_ROWS, -1);
        if(totalRows<resultList.size()){
            totalRows= resultList.size();
        }
        if(resultList instanceof PagedArrayList){
            ((PagedArrayList<?>) resultList).setTotal(totalRows);
            return resultList;
        }else{
            List totalList = new PagedArrayList(resultList, totalRows);
            return totalList;
        }
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties=properties;
    }

    /*<br>    *如果参数是String，则添加单引号， 如果是日期，则转换为时间格式器并加单引号； 对参数是null和不是null的情况作了处理<br>　　*/
    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(new Date()) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
        }
        return value;
    }

    public static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();  // 获取参数
        List<ParameterMapping> parameterMappings = boundSql
                .getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");  // sql语句中多个空格都用一个空格代替
        if (!CollectionUtils.isEmpty(parameterMappings) && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); // 获取类型处理器注册器，类型处理器的功能是进行java类型和数据库类型的转换<br>　　　　　　　// 如果根据parameterObject.getClass(）可以找到对应的类型，则替换
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));

            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);// MetaObject主要是封装了originalObject对象，提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);  // 该分支是动态sql
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else {
                        sql = sql.replaceFirst("\\?", "缺失");//TODO
                    }//打印出缺失，提醒该参数缺失并防止错位
                }
            }
        }
        return sql;
    }

    //将sql信息输入到requestInfoModel 中，以便统一日志插入数据库查询
    private void addSql2RequstInfo(String sql){
        if(logAspect==null)return;
        RequestInfoModel resqInfo = null;
        try{
            resqInfo = logAspect.getRequestInfoModel();
        }catch (Exception e){
        }
        try{
            if(resqInfo == null){
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                resqInfo = (RequestInfoModel) attributes.getRequest().getAttribute("resqInfo");
            }
        }catch (Exception e){
        }
        if(resqInfo != null){
            resqInfo.addSql(sql);
            try {
                logAspect.setRequestInfoModel(resqInfo);
            } catch (Exception e) {
            }
        }else {
            log.warn("mybatis拦截器获取请求信息失败!");
        }

    }

    private static Map<String, Object> convertObjectToMap(Object object) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = object.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            Object value = field.get(object);
            map.put(field.getName(), value);
        }
        return map;
    }
}
